package com.tanchengjin.admin.modules.blog.validations.annotation;

import com.google.code.kaptcha.Constants;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CaptchaValidator implements ConstraintValidator<Captcha, String> {

    @Override
    public void initialize(Captcha constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        ServletRequestAttributes httpServlet = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

        String code = (String) httpServlet.getRequest().getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

        if (null == code || code.isEmpty()) {
            return false;
        }

        return code.equalsIgnoreCase(s);
    }
}
